﻿using RSAExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace KWT.DRG_DIP.Common
{
    /// <summary>
    /// 加解密
    /// </summary>
    public static class _Security
    {
        public static class Sha1
        {
            public static string Encrypt(string str)
            {
                var bytes = Encoding.UTF8.GetBytes(str);
                var data = SHA1.Create().ComputeHash(bytes);

                var sb = new StringBuilder();
                foreach (var t in data)
                {
                    sb.Append(t.ToString("X2"));
                }

                return sb.ToString();
            }
        }

        public static class SHA256
        {
            public static string Encrypt(string key, string content)
            {
                using var sha256 = new HMACSHA256(Encoding.UTF8.GetBytes(key));
                byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(content));
                return Convert.ToBase64String(bytes);
            }
        }

        public static class Salt
        {
            public static string Encrypt(string pwd, string salt)
            {
                using var sha256 = new HMACSHA256(Encoding.UTF8.GetBytes("HYJK"));
                byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(pwd + salt));
                return Convert.ToBase64String(bytes);
            }
        }

        public static class Rsa
        {
            public static string Decrypt(string en_str)
            {
                using var rsa = RSA.Create();
                string private_key = _Config.GetValue<string>("RSA:PrivateKey");
                rsa.ImportPrivateKey(RSAKeyType.Pkcs1, private_key);
                return rsa.DecryptBigData(en_str, RSAEncryptionPadding.Pkcs1);
            }

            public static string Encrypt(string str)
            {
                using var rsa = RSA.Create();
                string public_key = _Config.GetValue<string>("RSA:PublicKey");
                rsa.ImportPublicKey(RSAKeyType.Pkcs8, public_key);
                return rsa.EncryptBigData(str, RSAEncryptionPadding.Pkcs1);
            }
        }

        public static class Md5
        {
            public static string Encrypt(string str)
            {
                byte[] bt = Encoding.UTF8.GetBytes(str);
                var md5 = MD5.Create();
                var md5bt = md5.ComputeHash(bt);
                var builder = new StringBuilder();
                foreach (var item in md5bt)
                {
                    builder.Append(item.ToString("X2"));
                }
                return builder.ToString().ToLower();
            }
        }

    }
}
